package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author: fd
 * @Date 2021/9/16 17:08
 * @Description: 定时关闭订单
 */
@RabbitListener(queues = "order.release.order.queue")
@Service
public class OrderCloseListener {

	private final OrderService orderService;

	private final AlipayTemplate alipayTemplate;

	public OrderCloseListener(OrderService orderService, AlipayTemplate alipayTemplate) {
		this.orderService = orderService;
		this.alipayTemplate = alipayTemplate;
	}

	@RabbitHandler
	public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
		System.out.println("收到过期的订单信息，准备关闭订单" + orderEntity.getOrderSn());
		try {
			orderService.closeOrder(orderEntity);
			// TODO 调用支付宝手动关闭订单接口
			alipayTemplate.closeAliPay(orderEntity);
			channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		} catch (Exception e) {
			channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
		}
	}
}